<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2020/1/3
// +----------------------------------------------------------------------

namespace app\command;

use app\common\facade\Arr;
use app\common\services\statistics\BehaviorHandleService;
use app\common\services\statistics\HomePageHandleService;
use app\common\services\statistics\JobHandleService;
use app\common\services\statistics\MarketHandleService;
use app\common\services\statistics\NewsHandleService;
use app\common\services\statistics\UserHandleService;
use think\console\Input;
use think\console\Output;
use think\Db;

/**
 * 分析处理用户行为记录
 * Class UserBehaviorCommand
 * @package app\command
 * @author feraner<feraner@163.com>
 * @date 2020/1/3
 */
class UserBehaviorCommand extends BasicCommand
{

    protected $name = 'behavior:analysis';

    protected $desc = '分析用户行为命令';

    /**
     * 处理模块集
     * @var array
     */
    protected $plugins = [
        'jobHandle',
        'userHandle',
        'marketHandle',
        'newsHandle',
        'commonHandler',
        'homeHandle'
    ];

    /**
     * @var UserHandleService|null
     */
    private $userHandle = null;
    /**
     * @var JobHandleService|null
     */
    private $jobHandle = null;
    /**
     * @var MarketHandleService|null
     */
    private $marketHandle = null;
    /**
     * @var NewsHandleService|null
     */
    private $newsHandle = null;

    /**
     * @var HomePageHandleService|null
     */
    private $homeHandle = null;

    /**
     * @var BehaviorHandleService|null
     */
    private $commonHandler = null;

    /**
     * 是否需要处理总量+ 月度数据统计
     * @var bool
     */
    private $handleMonthAndTotal = false;


    public function __construct($name = null)
    {
        parent::__construct($name);

        $this->userHandle = new UserHandleService();
        $this->jobHandle = new JobHandleService();
        $this->marketHandle = new MarketHandleService();
        $this->newsHandle = new NewsHandleService();
        $this->commonHandler = new BehaviorHandleService();
        $this->homeHandle = new HomePageHandleService();


    }


    /**
     * @param Input  $input
     * @param Output $output
     *
     * @return int|null|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    protected function execute(Input $input, Output $output)
    {
        while (true) {
            $behaviorList = $this->__getHandleList();
            if ($behaviorList) {
                foreach ($behaviorList as $item) {
                    $this->__handleOneBehavior($item);
                }
                //设置处理完成
                $this->__setHandleDone($behaviorList);
                $this->handleMonthAndTotal = true;

                unset($behaviorList);
            } else {
                break;
            }
        }

        if ($this->handleMonthAndTotal) {
            try {
                //有日度数据更新再处理月度数据 + 总量
                foreach ($this->plugins as $item) {
                    $this->$item->handleMonthAndTotal();
                }
            } catch (\Exception $e) {
                //不处理
            }

        }
    }


    /**
     * 处理一条用户行为
     * @param $behavior
     */
    private function __handleOneBehavior($behavior)
    {
        try {
            $url = Arr::get($behavior, 'url');
            $paramsArr = json_decode(Arr::get($behavior, 'params'), true);
            $urlArr = array_values(array_filter(explode('/', $url)));

            $handleData = [
                'url'       => $url,
                'urlArr'    => $urlArr,
                'params'    => $paramsArr,
                'userId'    => Arr::get($behavior, 'user_id', 0),
                'ip'        => Arr::get($behavior, 'ip'),
                'method'    => Arr::get($behavior, 'method'),
                'logId'     => Arr::get($behavior, 'id')
            ];
            foreach ($this->plugins as $item) {
                $this->$item->handle($handleData);
            }
        } catch (\Exception $e) {
            //不处理
        }

    }


    /**
     * 设置记录处理完成
     * @param $list
     *
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function __setHandleDone($list)
    {
        $idArr = array_column($list, 'id');
        Db::name('user_behavior_log')
            ->where('status', 0)
            ->where('id', 'IN', $idArr)
            ->update([
                'status'        => 1,
                'updated_at'    => time()
            ]);
    }






    /**
     * 获取需要处理的用户行为记录
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function __getHandleList()
    {
        return Db::name('user_behavior_log')
            ->where('status', 0)
            ->limit(0, 50)
            ->select() ?: [];
    }







}
